#include <input_manager.h>
#include <tslib.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <input_manager.h>
#define SERVER_PORT 8888
static int g_iSocket_fd;
static int DeviceInit_NetInputDev()
{
	struct sockaddr_in tSocketServerAddr;
	int iRet;
	g_iSocket_fd = socket(AF_INET , SOCK_DGRAM , 0);
	if(-1 == g_iSocket_fd)
	{
		printf("socket err\n");
		return -1;
		
	}
	memset(&tSocketServerAddr , 0 , sizeof(tSocketServerAddr));
	tSocketServerAddr.sin_family 		= AF_INET;
	tSocketServerAddr.sin_port   		= htons(SERVER_PORT);
	tSocketServerAddr.sin_addr.s_addr 	= INADDR_ANY;

	iRet = bind(g_iSocket_fd ,(struct sockaddr *)&tSocketServerAddr , sizeof(struct sockaddr));
	if(-1 == iRet)
	{
		printf("bind err\n");
		return -1;
	}
	return 0;
}

static int GetInputEvent_NetInputDev(PInputEvent ptInputEvent)
{
	struct sockaddr_in tSocketClientAddr;
	char aRcvBuf[1024];
	socklen_t iAddrLen = sizeof(struct sockaddr);
	ssize_t iRecvlen;

	memset(aRcvBuf , 0 , 1024);

	iRecvlen = recvfrom(g_iSocket_fd , aRcvBuf , 1024 , 0 , (struct sockaddr *)&tSocketClientAddr , &iAddrLen );
	if(iRecvlen > 0)
	{
		aRcvBuf[iRecvlen] = '\0';
		ptInputEvent->iType 		= INPUT_TYPE_NET;
		gettimeofday(&ptInputEvent->tTime , NULL);
		strncpy(ptInputEvent->str , aRcvBuf , 1024);	
		ptInputEvent->str[1023] = '\0'; 
		return 0;
	}
	else
		return -1;
}

static int DeviceExit_NetInputDev()
{
	close(g_iSocket_fd);
	return 0;
}
static InputDevice g_tNetInputDev = {
	.name				="NetInput",
	.GetInputEvent		=GetInputEvent_NetInputDev,
	.DeviceInit			=DeviceInit_NetInputDev,
	.DeviceExit			=DeviceExit_NetInputDev,
};
void NetInputDev_Register(void)
{
	Register_InputDevice(&g_tNetInputDev);
}

